package org.example.webservice.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

/**
 * 自定义错误控制器
 */
@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        // 获取错误状态码
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        
        if (status != null) {
            Integer statusCode = Integer.valueOf(status.toString());
            
            // 根据不同的错误状态码设置不同的错误信息，这是统一的异常处理
            switch (statusCode) {
                case 404:
                    model.addAttribute("errorTitle", "页面未找到");
                    model.addAttribute("errorMessage", "抱歉，您访问的页面不存在。");
                    break;
                case 500:
                    model.addAttribute("errorTitle", "服务器内部错误");
                    model.addAttribute("errorMessage", "服务器遇到了一个错误，请稍后再试。");
                    break;
                case 403:
                    model.addAttribute("errorTitle", "访问被拒绝");
                    model.addAttribute("errorMessage", "您没有权限访问此资源。");
                    break;
                default:
                    model.addAttribute("errorTitle", "发生错误");
                    model.addAttribute("errorMessage", "系统遇到了一个错误，请稍后再试。");
                    break;
            }
            
            model.addAttribute("statusCode", statusCode);
        } else {
            model.addAttribute("errorTitle", "未知错误");
            model.addAttribute("errorMessage", "系统遇到了一个未知错误。");
            model.addAttribute("statusCode", "未知");
        }
        
        // 获取错误异常信息（如果有的话）
        Object exception = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
        if (exception != null) {
            model.addAttribute("exception", exception.toString());
        }
        
        return "error";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}